package com.telit.firecommand.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.telit.common.entity.DataReturn;
import com.telit.common.enums.ResultCode;
import com.telit.firecommand.dao.CommFireRiskLevelDao;
import com.telit.firecommand.dto.CommFireRiskLevelDto;
import com.telit.firecommand.dto.FireWarnDto;
import com.telit.firecommand.entity.CommFireRiskLevel;
import com.telit.firecommand.service.CommFireRiskLevelService;
import com.telit.firecommand.vo.FireLevelNumVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 火险等级管理
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CommFireRiskLevelServiceImpl extends ServiceImpl<CommFireRiskLevelDao, CommFireRiskLevel> implements CommFireRiskLevelService {

    /**
     * 添加火险等级
     *
     * @param dto
     * @return
     */
    @Override
    public DataReturn add(CommFireRiskLevelDto dto) {
        if (null != dto && CollectionUtil.isNotEmpty(dto.getFireRiskLevelList())) {
            //防火季名称不能重复
            int num = baseMapper.getByName(dto.getFireSeasonName());
            if (num > 0) {
                return DataReturn.failure(ResultCode.REQUEST_PARAMS_CHECK_ERROR, "当前防火季名称已存在！");
            }
            //默认不发布
            String isRelease = (null == dto.getIsRelease()) ? "0" : dto.getIsRelease();
            //如果点击“发布”按钮，需要将其他防火季名称火险等级数据发布状态改为“0”
            if ("1".equals(isRelease)) {
                baseMapper.updateAllNoRelease();
            }
            List<CommFireRiskLevel> list = dto.getFireRiskLevelList();
            list = list.stream().filter(l -> StringUtils.isNotEmpty(l.getLevel())).collect(Collectors.toList());
            //表单提交数据与数据库数据为“一对多”
            list.forEach(l -> {
                l.setFireSeasonName(dto.getFireSeasonName());
                l.setStartTime(dto.getStartTime());
                l.setEndTime(dto.getEndTime());
                l.setCreateTime(new Date());
                l.setUpdateTime(LocalDateTime.now());
                l.setIsRelease(isRelease);
                l.setProvince(l.getDistrictCode().substring(0,2));
                l.setCity(l.getDistrictCode().substring(0,4));
                l.setCounty(l.getDistrictCode().substring(0,6));
                l.setCountryside(l.getDistrictCode().substring(0,9));
            });
            int i = baseMapper.insertBatch(list);
            return DataReturn.ok(i);
        }
        return DataReturn.failure(ResultCode.BAD_REQUEST);
    }

    /**
     * 分页查询火险等级
     *
     * @param page
     * @param rows
     * @param fireSeasonName
     * @return
     */
    @Override
    public DataReturn selectByPage(Integer page, Integer rows, String fireSeasonName) {
        IPage<CommFireRiskLevel> commFireRiskLevelIPage = new Page<>(page, rows);
        IPage<CommFireRiskLevel> iPage = baseMapper.selectByPage(commFireRiskLevelIPage, fireSeasonName);
        return DataReturn.ok(iPage);
    }

    /**
     * 根据防火季名称查询火险等级详情
     *
     * @param fireSeasonName
     * @return
     */
    @Override
    public DataReturn queryByName(String fireSeasonName) {
        QueryWrapper<CommFireRiskLevel> wrapper = new QueryWrapper<CommFireRiskLevel>();
        wrapper.eq("fire_season_name", fireSeasonName);
        List<CommFireRiskLevel> list = baseMapper.selectList(wrapper);
        CommFireRiskLevelDto dto = new CommFireRiskLevelDto();
        if (CollectionUtil.isNotEmpty(list)) {
            dto.setFireSeasonName(list.get(0).getFireSeasonName());
            dto.setStartTime(list.get(0).getStartTime());
            dto.setEndTime(list.get(0).getEndTime());
            dto.setIsRelease(list.get(0).getIsRelease());
            FireWarnDto shiDto = new FireWarnDto();
            shiDto.setCode("4205");
            shiDto.setName("宜昌市");
            List<String> xianList = baseMapper.queryAllXian();
            if(null != xianList) {
                List<FireWarnDto> xianDtoList = new ArrayList<>();
                xianList.forEach(xian -> {
                    FireWarnDto xianDto = new FireWarnDto();
                    xianDto.setCode(xian);
                    xianDto.setName(baseMapper.getXianName(xian));
                    List<String> xiangList = baseMapper.queryAllXiangByXian(xian);
                    if(null != xiangList) {
                        List<FireWarnDto> xiangDtoList = new ArrayList<>();
                        xiangList.forEach(xiang -> {
                            FireWarnDto xiangDto = new FireWarnDto();
                            xiangDto.setCode(xiang);
                            xiangDto.setName(baseMapper.getXiangName(xiang));
                            xiangDto.setLevel(baseMapper.getLevelWhetherByXiang(xiang, dto.getFireSeasonName()));
                            xiangDtoList.add(xiangDto);
                        });
                        xianDto.setChildren(xiangDtoList);
                    }
                    xianDtoList.add(xianDto);
                });
                shiDto.setChildren(xianDtoList);
            }
            dto.setFireWarnDto(shiDto);
        }
        return DataReturn.ok(dto);
    }

    /**
     * 编辑火险等级数据
     *
     * @param dto
     * @return
     */
    @Override
    public DataReturn updateByName(CommFireRiskLevelDto dto) {
        //根据oldFireSeasonName删除之前的数据后，重新添加数据
        if (null != dto && StringUtils.isNotEmpty(dto.getOldFireSeasonName())) {
            baseMapper.deleteByName(dto.getOldFireSeasonName());
        }
        return add(dto);
    }

    /**
     * 根据防火季名称删除火险等级详情
     *
     * @param fireSeasonName
     */
    @Override
    public void deleteByName(String fireSeasonName) {
        baseMapper.deleteByName(fireSeasonName);
    }

    /**
     * 发布按钮功能
     *
     * @param fireSeasonName
     */
    @Override
    public void release(String fireSeasonName, String isRelease) {
        if("1".equals(isRelease)) {
            baseMapper.updateAllNoRelease();
        }
        baseMapper.updateReleaseByName(fireSeasonName, isRelease);
    }

    /**
     * 火险预警数据
     * @return
     */
    @Override
    public Object getFireWarning(String districtCode) {
        FireWarnDto dto = new FireWarnDto();
        //获取发布的防火季名称
        String fireSeasonName = baseMapper.getReleaseFireSeasonName(districtCode);
        if(StringUtils.isEmpty(fireSeasonName)) {
            return null;
        }
        dto.setCode("4205");
        dto.setName("宜昌市");
//        dto.setFireSeasonName(fireSeasonName);
        //获取县代码
        List<String> xianList = baseMapper.queryXianInfoByShi(districtCode,"4205");
        if(null != xianList) {
            List<FireWarnDto> xianDtoList = new ArrayList<>();
            xianList.forEach(xian -> {
                FireWarnDto xianDto = new FireWarnDto();
                xianDto.setCode(xian);
                xianDto.setName(baseMapper.getXianName(xian));
                //获取乡镇代码
                List<String> xiangList = baseMapper.queryXiangInfoByXian(districtCode, xian);
                if(null != xiangList) {
                    List<FireWarnDto> xiangDtoList = new ArrayList<>();
                    xiangList.forEach(xiang -> {
                        FireWarnDto xiangDto = new FireWarnDto();
                        xiangDto.setCode(xiang);
                        xiangDto.setName(baseMapper.getXiangName(xiang));
                        xiangDto.setLevel(baseMapper.getLevelByXiang(xiang));
                        xiangDtoList.add(xiangDto);
                    });
                    xianDto.setChildren(xiangDtoList);
                }
                xianDtoList.add(xianDto);
            });
            dto.setChildren(xianDtoList);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("fireSeasonName", fireSeasonName);
        map.put("fireWarnDto", dto);
        return map;
    }

    /**
     * 获取火险等级饼状图统计数据
     * @param districtCode
     * @return
     */
    @Override
    public Object getFireLevelNum(String districtCode) {
        List<FireLevelNumVo> list = baseMapper.getFireLevelNum(districtCode);
        int count = 0;
        for (FireLevelNumVo vo: list) {
            count = count + Integer.parseInt(vo.getValue());
        }
        for (FireLevelNumVo vo: list) {
            BigDecimal p = new BigDecimal(vo.getValue()).divide(new BigDecimal(count),2,BigDecimal.ROUND_HALF_UP).setScale(2, RoundingMode.HALF_UP);
            vo.setPercent(String.valueOf(p));
        }
        return list;
    }

}

